<template>
  <div style="padding-top: -10px;">
    <a-button @click="visible=true" style="margin-bottom:5px;">多人搜索</a-button>
    <a-transfer
      :data-source="mockData"
      :target-keys="targetKeys"
      :disabled="disabled"
      :show-search="showSearch"
      :filter-option="filterOption"
      :show-select-all="false"
      @change="onChange"
      @search="onSearch"
      @selectChange="selectChange"
    >
      <template
        slot="children"
        slot-scope="{
          props: { direction, filteredItems, selectedKeys, disabled: listDisabled },
          on: { itemSelectAll, itemSelect }
        }"
      >
        <a-table
          :row-selection="getRowSelection({ disabled: listDisabled, selectedKeys, itemSelectAll, itemSelect })"
          :columns="tabColumns"
          :data-source="filteredItems"
          size="small"
          :style="{ pointerEvents: listDisabled ? 'none' : null }"
          :pagination="direction === 'left' ? paginationLeft : paginationRight"
          @change="pageChange"
          :custom-row="
            ({ key, disabled: itemDisabled }) => ({
              on: {
                click: () => {
                  if (itemDisabled || listDisabled) return;
                  itemSelect(key, !selectedKeys.includes(key));
                }
              }
            })
          "
        />
      </template>
    </a-transfer>
    <a-modal
            title="批量搜索"
            :visible="visible"
            :closable="false"
            @ok="handleOk"
            @cancel="handleCancel"
            width="400px"
    >
      <div>
        <a-textarea v-model="names" placeholder="请输入多个人名，用逗号隔开。" :rows="5" />
      </div>
    </a-modal>
  </div>
</template>
<script>
import difference from 'lodash/difference';
import { getRiskAction } from '@/api/manage';
import debounce from 'lodash/debounce';
export default {
  props: {
    url: {
      Type: String,
      default: ''
    },
    keyName: {
      Type: String,
      default: 'id'
    },
    tabColumns: {
      Type: Array,
      default: () => []
    },
    originTargetKeys: {
      Type: Array,
      default: () => []
    }
  },
  watch: {},
  data() {
    this.onSearch = debounce(this.onSearch, 500);
    return {
      mockData: [],
      keyword: '',
      names: '',
      targetKeys: [],
      targetRows: [],
      disabled: false,
      showSearch: true,
      paginationLeft: {
        defaultCurrent: 1,
        defaultPageSize: 10,
        total: 0
      },
      paginationRight: {
        defaultCurrent: 1,
        defaultPageSize: 9,
        pageSize: 10,
        total: 0
      },
      visible:false
    };
  },
  methods: {
    pageChange(page) {
      if (page.defaultPageSize == 10) {
        this.initMockData(page.current);
      }
    },
    filterOption(inputValue, option) {
      return option.username.indexOf(inputValue) > -1 || option.realname.indexOf(inputValue) > -1;
    },
    onChange(nextTargetKeys) {
      this.targetKeys = nextTargetKeys;
      this.targetRows = [];
      this.mockData.forEach(item => {
        if (this.targetKeys != null && this.targetKeys.length > 0 && this.targetKeys.indexOf(item.key) > -1) {
          this.targetRows.push(item);
        }
      });
      this.paginationLeft.current = 1;
      this.names='';
      this.initMockData(1);
    },
    onSearch(direction, value) {
      debugger
      this.names='';
      if (direction == 'left') {
        this.keyword = value;
        this.initMockData(1);
      }
    },
    getRowSelection({ disabled, selectedKeys, itemSelectAll, itemSelect }) {
      return {
        getCheckboxProps: item => ({ props: { disabled: disabled || item.disabled } }),
        onSelectAll(selected, selectedRows) {
          const treeSelectedKeys = selectedRows.filter(item => !item.disabled).map(({ key }) => key);
          const diffKeys = selected
            ? difference(treeSelectedKeys, selectedKeys)
            : difference(selectedKeys, treeSelectedKeys);
          itemSelectAll(diffKeys, selected);
        },
        onSelect({ key }, selected) {
          itemSelect(key, selected);
        },
        selectedRowKeys: selectedKeys
      };
    },
    initMockData(curr) {
      var vm = this;
      vm.mockData = [];
      if (vm.targetRows != null && vm.targetRows.length > 0) {
        vm.mockData = JSON.parse(JSON.stringify(vm.targetRows));
      }
      getRiskAction(this.url, { keyword: this.keyword,pageNo: curr, pageSize: 10, targetKeys: this.targetKeys.join(','),names:this.names })
        .then(res => {
          if (res.code == 0 || res.code == 200 || res.success) {
            vm.paginationLeft.total = res.data.total;
            if (res.data != null && res.data.records != null) {
              res.data.records.forEach(record => {
                record.key = record[vm.keyName];
                vm.mockData.push(record);
              });
              vm.paginationLeft.defaultCurrent = curr;
              vm.paginationLeft.current = curr;
            } else {
              vm.$message.warning('加载穿梭框选项为空');
            }
          } else {
            vm.$message.warning('加载穿梭框选项异常:' + (res.message || res.msg));
          }
        })
        .catch(res => {
          vm.$message.warning('加载穿梭框选项出错:' + (res.message || res.msg));
        });
    },
    handleOk(){
      this.visible=false;
      this.initMockData(1);
    },
    handleCancel(){
      this.visible=false;
    },
    clearTargetKey(){
      this.targetKeys = [];
    },
    selectChange(sourceSelectedKeys, targetSelectedKeys){
      if(sourceSelectedKeys.length >0){
        const that = this;
       sourceSelectedKeys.forEach(item=>{
          if(that.targetKeys.indexOf(item<=0)){
            that.targetKeys.push(item);
          }
        });
        this.targetRows = [];
        that.mockData.forEach(item => {
          if (that.targetKeys != null && this.targetKeys.length > 0 && this.targetKeys.indexOf(item.key) > -1) {
            that.targetRows.push(item);
          }
        });
      } 
    },
     initOriginTargetKeys() {
      if ( this.originTargetKeys == null || this.originTargetKeys.length < 1) {
        this.initMockData(1)
        //搜索框聚焦
        $('.ant-transfer-list-search')[0].focus()
        return
      }
      var vm = this
      getRiskAction(this.url, { contaionKeys: this.originTargetKeys.join(',') })
        .then((res) => {
          if (res.code == 0 || res.code == 200 || res.success) {
            if (res.data != null) {
              res.data.records.forEach((record) => {
                record.key = record[vm.keyName]
                vm.targetRows.push(record)
                vm.targetKeys.push(record.key)
                vm.mockData.push(record)
              })
            }
          } else {
            vm.$message.warning('初始化穿梭框已选选项异常:' + (res.message || res.msg))
          }
          vm.initMockData(1)
        })
        .catch((res) => {
          vm.$message.warning('初始化穿梭框已选选项出错:' + (res.message || res.msg))
        })

      //搜索框聚焦
      $('.ant-transfer-list-search')[0].focus()
    },
    
  },
  mounted() {
    this.initOriginTargetKeys();
  }
};
</script>
<style scoped>
::v-deep  .ant-transfer-list-header {
  display: none;
}
::v-deep  .ant-transfer-list {
  padding: 10px;
}
</style>
